<template>
	<f7-page>
		<f7-navbar>
			<f7-nav-left>
				<f7-link @click="back">
					<f7-icon icon="icon-back" style="margin-left: 15px;"></f7-icon>
				</f7-link>
			</f7-nav-left>
			<f7-nav-title title="问题详情"></f7-nav-title>
			<f7-nav-right>
				<f7-badge color="red">待整改</f7-badge>&nbsp;&nbsp;
				<f7-badge color="pink" v-if="timeout">超时</f7-badge>
				<f7-badge color="yellow" v-if="isSendBack()">退回</f7-badge>
			</f7-nav-right>
		</f7-navbar>
		<f7-list inline-labels no-hairlines no-hairlines-between inset v-if="isSendBack()">
			<f7-list-item>
				<f7-label style="width:30%;">退回原因</f7-label>
				<f7-list-item-cell>
					{{checkQualityProblem.sentBackRemark}}
				</f7-list-item-cell>
			</f7-list-item>
			<f7-list-item>
				<f7-label style="width:30%;">退回照片</f7-label>
				<f7-list-item-cell>
					<img width="80" height="80" style="margin-right: 5px;" v-for="(imageFile, i) in checkQualityProblem.sentBackImageFile"
					 :src="imageFile.url" @click="$refs.sentBackPhotoBrowsers.open(i)">
					</img>
				</f7-list-item-cell>
				<f7-photo-browser :photos="checkQualityProblem.sentBackImageFile" type="popup" ref="sentBackPhotoBrowsers"
				 back-link-text="关闭">
				</f7-photo-browser>
			</f7-list-item>
		</f7-list>

		<f7-list inline-labels no-hairlines no-hairlines-between inset>
			<f7-list-item v-if="checkQualityProblem.bidSectionId != null">
				<f7-label style="width:30%;" v-if="checkQualityProblem.bidSectionId != null">标段</f7-label>
				<f7-list-item-cell>
					{{ $store.state.global.bidSectionMap[checkQualityProblem.bidSectionId].bid_section_name + '(' + $store.state.global.projectMap[$store.state.global.bidSectionMap[checkQualityProblem.bidSectionId].project_id].project_name + ')' }}
				</f7-list-item-cell>
			</f7-list-item>
			<f7-list-item>
				<f7-label style="width:30%;">部位</f7-label>
				<f7-list-item-cell>
					<f7-row>
						<f7-col width="70">{{checkQualityProblem.place}}</f7-col>
						<f7-col width="30" v-if="checkQualityProblem.roomId != null" @click.stop="openHousePoint($store.state.global.houseMap[checkQualityProblem.roomId])">
							<f7-badge color="blue">图</f7-badge>
						</f7-col>
					</f7-row>
				</f7-list-item-cell>
			</f7-list-item>
			<f7-list-item>
				<f7-label style="width:30%;">检查项</f7-label>
				<f7-list-item-cell>
					{{$store.state.global.problemClassMap[$store.state.global.problemClassMap[checkQualityProblem.problemClassId].parent_problem_class_id].problem_class_name
                    + ' - ' +
                    $store.state.global.problemClassMap[checkQualityProblem.problemClassId].problem_class_name}}
				</f7-list-item-cell>
			</f7-list-item>
			<f7-list-item>
				<f7-label style="width:30%;">描述</f7-label>
				<f7-list-item-cell>
					<f7-row v-if="checkQualityProblem.problemId != null">
						{{$store.state.global.problemMap[checkQualityProblem.problemId].problem_name}}
					</f7-row>
					<f7-row>
						{{checkQualityProblem.remark}}
					</f7-row>
				</f7-list-item-cell>
			</f7-list-item>
			<f7-list-item>
				<f7-label style="width:30%;">问题照片</f7-label>
				<f7-list-item-cell>
					<img width="80" height="80" style="margin-right: 5px;" v-for="(imageFile, i) in checkQualityProblem.imageFile"
					 :src="imageFile.url" @click="$refs.imageFile.open(i)">
					</img>
				</f7-list-item-cell>
				<f7-photo-browser :photos="checkQualityProblem.imageFile" type="popup" ref="imageFile" back-link-text="关闭">
				</f7-photo-browser>
			</f7-list-item>
			<f7-list-item>
				<f7-label style="width:30%;">提交人</f7-label>
				<f7-list-item-cell>
					{{$store.state.global.userMap[checkQualityProblem.registBy].realname}}&nbsp;
					{{formateDate(checkQualityProblem.registDate)}}
				</f7-list-item-cell>
			</f7-list-item>
			<f7-list-item>
				<f7-label style="width:30%;">整改期限</f7-label>
				<f7-list-item-cell>
					{{formateDate(checkQualityProblem.repairDeadline)}}
				</f7-list-item-cell>
			</f7-list-item>
			<f7-list-item v-show="!isRepairUser() || (!isOnline && isRepairUser())">
				<f7-label style="width:30%;">整改人</f7-label>
				<f7-list-item-cell>
					{{$store.state.global.userMap[checkQualityProblem.repair].realname}}
				</f7-list-item-cell>
			</f7-list-item>
			<f7-list-item v-show="isRepairUser() && isOnline" id="repairUserSmartSelect" smart-select :smart-select-params="{openIn: 'popup', closeOnSelect: true, searchbar: true, searchbarPlaceholder: '搜索', searchbarDisableText: '取消', popupCloseLinkText: '返回'}">
				<f7-label>整改人</f7-label>
				<select v-model="form.repair.userId">
					<optgroup label="施工单位">
						<option v-for="(userId, i) in contractors" :key="userId" :value="userId" v-text="$store.state.global.userMap[userId].realname">
						</option>
					</optgroup>
					<optgroup label="监理单位">
						<option v-for="(userId, i) in supervisors" :key="userId" :value="userId" v-text="$store.state.global.userMap[userId].realname">
						</option>
					</optgroup>
					<optgroup label="建设单位">
						<option v-for="(userId, i) in constructors" :key="userId" :value="userId" v-text="$store.state.global.userMap[userId].realname">
						</option>
					</optgroup>
				</select>
			</f7-list-item>
			<f7-list-item v-if="isRepairUser()">
				<TakePhoto ref="refTakePhoto" @photoAdd="photoAdd" @photoDelete="photoDelete"></TakePhoto>
			</f7-list-item>
			<f7-list-item v-if="isRepairUser()">
				<f7-input type="textarea" label="整改说明" placeholder="整改说明" :value="form.remark" @change="form.remark = $event.target.value">
				</f7-input>
			</f7-list-item>
			<f7-list-item>
				<f7-label style="width:30%;">责任单位</f7-label>
				<f7-list-item-cell>
					{{checkQualityProblem.contractorId == null ? '':$store.state.global.contractorMap[checkQualityProblem.contractorId].contractor_short_name}}
				</f7-list-item-cell>
			</f7-list-item>
			<f7-list-item>
				<f7-label style="width:30%;">复验人</f7-label>
				<f7-list-item-cell>
					<span v-for="(user, i) in checkQualityProblem.reinspect" style="margin-right:4px;">
                    	{{$store.state.global.userMap[user].realname}}
                	</span>
				</f7-list-item-cell>
			</f7-list-item>
			<f7-list-item v-if="checkQualityProblem.ccs.length != 0">
				<f7-label style="width:30%;">抄送人</f7-label>
				<f7-list-item-cell>
					<span v-for="(user, i) in checkQualityProblem.ccs" style="margin-right:4px;">
						{{$store.state.global.userMap[user].realname}}
					</span>
				</f7-list-item-cell>
			</f7-list-item>
			<f7-list-item v-if="isRepairUser()">
				<f7-list-item-cell width="50">
					<f7-button big round @click="saveTemporary">暂存</f7-button>
				</f7-list-item-cell>
				<f7-list-item-cell width="50" v-show="isOnline">
					<f7-button big round @click="ensureSunmit">完成整改</f7-button>
				</f7-list-item-cell>
			</f7-list-item>
			<f7-list-item v-if="isRegistUser()">
				<f7-list-button title="非正常关闭" style="width:100%;" color="red" @click="abnormalClose"></f7-list-button>
			</f7-list-item>
		</f7-list>

		<f7-popup id="abnormalClosePopup" :backdrop="false" :close-by-backdrop-click="false">
			<f7-page>
				<f7-navbar>
					<f7-nav-left>
						<f7-link href="#" @click="$f7.popup.close('#abnormalClosePopup', true);">取消</f7-link>
					</f7-nav-left>
					<f7-nav-title title="选择关闭原因"></f7-nav-title>
				</f7-navbar>
				<f7-list>
					<f7-list-item radio v-for="item in closes"
					name="closeReason"
					:checked="closeReason === item"
					:key="item"
					:value="item"
					:title="item"
					@change="closeReason = $event.target.value"
					></f7-list-item>
					<f7-list-item v-if="closeReason == '其它'">
						<f7-input type="textarea" rows="2" placeholder="补充说明" :value="closeRemark" @change="closeRemark = $event.target.value">
						</f7-input>
					</f7-list-item>
					<!-- <f7-list-item radio name="closeReason" :checked="closeReason === '问题登记错误'" value="问题登记错误" title="问题登记错误" @change="closeReason = $event.target.value"></f7-list-item>
					<f7-list-item radio name="closeReason" :checked="closeReason === '已整改并复验通过'" value="已整改并复验通过" title="已整改并复验通过" @change="closeReason = $event.target.value"></f7-list-item>
					<f7-list-item radio name="closeReason" :checked="closeReason === '无法整改'" value="无法整改" title="无法整改" @change="closeReason = $event.target.value"></f7-list-item>
					<f7-list-item radio name="closeReason" :checked="closeReason === 4" value="4" title="延误整改窗口期" @change="closeReason = $event.target.value"></f7-list-item>
					<f7-list-item radio name="closeReason" :checked="closeReason === 5" value="5" title="留待后期整改" @change="changecloseReason = $event.target.valueCloseReson"></f7-list-item>
					<f7-list-item radio name="closeReason" :checked="closeReason === 6" value="6" title="其它" @change="closeReason = $event.target.value"></f7-list-item>
					<f7-list-item v-if="closeReason == 6">
						<f7-input type="textarea" rows="2" placeholder="补充说明" :value="closeRemark" @change="closeRemark = $event.target.value">
						</f7-input>
					</f7-list-item> -->
					<f7-list-item>
						<f7-list-item-cell>
							<f7-button style="width:70%;margin-right:auto;margin-left:auto;" @click="ensureAbnormalCloseSubmit">提交</f7-button>
						</f7-list-item-cell>
					</f7-list-item>
				</f7-list>
			</f7-page>
		</f7-popup>
	</f7-page>
</template>

<script>
	
	import networkEvent from '@/mixins/networkEvent';
	import back from '@/mixins/back.js';
	import Common from "@/utils/Common.js";
	import DateUtil from "@/utils/DateUtil.js";
	import FileUtil from "@/utils/FileUtil.js";
	import events from 'events';
	import eventBus from '@/utils/eventBus.js';
	import store from '@/store';
	import {getUser, setUser, clearUser} from '@/utils/auth';
	import {getStore, setStore, clearStore} from '@/utils/storage';
	import keys from '@/utils/rememberKeys';
	import request from '@/utils/request';
	import db from '@/utils/db';
	import TakePhoto from "@/components/TakePhoto.vue";
	import { upload, uploadImage } from '@/utils/upload';
	export default {
		mixins: [networkEvent, back],
		store: store,
		components: {
			TakePhoto,
		},
		props: {
			checkQualityProblem: {
				type: Object
			},
			sourceIsUnprocessed: {
				type: Boolean,
				default: false
			}
		},
		data: function() {
			return {
				form: {
					tid: null,
					checkQualityProblemId: null,
					photos: [],
					remark: '',
					repair: {
						userId: '',
					}
				},
				selection: {
					project: {},
				},
				deletePhotos: [],
				contractors: [],
				supervisors: [],
				constructors: [],
				closeRemark: "",
				closeReason:"",
				closes:["问题登记错误","已整改并复验通过","无法整改","延误整改窗口期",'留待后期整改',"其它"]
			};
		},
		methods: {
			ensureSunmit: function() {
				var self = this;
				this.$f7.dialog.confirm("您确定完成整改？", "", function() {
					self.submit();
				});
			},
			submit: function() {
				var self = this;
				self.$f7.preloader.show();
				let dialog = self.$f7.dialog.progress('上传图片中', 0);
				dialog.finishCount = 0;
				let data = {
					checkQualityProblemId: self.checkQualityProblem.id,
					repairUserId: getUser().userId,
					repairRemark: self.form.remark,
					photos: []
				};
				let promises = [];
				self.form.photos.forEach(photoPath => {
                	let promise = FileUtil.read(photoPath, 'image/jpeg').then(blob => {
                		let splits = photoPath.split("/");
                		let filename = splits[splits.length - 1];
                		return uploadImage(filename, blob);
                	}).then(result => {
                		data.photos.push(result.url);
                		dialog.finishCount++;
                		dialog.setProgress(parseInt(dialog.finishCount / (self.form.photos.length + 1)) * 100);
                		return Promise.resolve();
                	});
                	promises.push(promise);
                });
				Promise.all(promises).then(() => {
					return request({
                		url: '/api/checkQualityProblem/problemRepair',
						method: 'post',
						data: data,
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded'
						} //参数不能太复杂，数组只能是一维数组
                	});
				}).then(result => {
					dialog.close();
					self.$f7.dialog.alert(result.detail.msg, '问题修复成功！');
					self.$f7router.back();
					self.$f7router.emit('problemStautsChange', result.element);
					if (self.form.tid != null) {
						self.$f7router.emit('deleteProblemRepair', self.form.tid);
					}
					self.$f7.preloader.hide();
				}).catch(error => {
					dialog.close();
					self.$f7.dialog.alert('', '提交问题失败！');
                	self.saveTemporary();
                	console.error(error);
				});
			},
			abnormalClose: function() {
				this.closeRemark = '';
				this.$f7.popup.open('#abnormalClosePopup', true);
			},
			photoAdd: function(filePath) {
				this.form.photos.push(filePath);
			},
			photoDelete: function(filePath) {
				for (var i = 0; i < this.form.photos.length; i++) {
					if (filePath == this.form.photos[i]) {
						this.form.photos.splice(i, 1);
						if (filePath.indexOf(Common.directory().localeCheck) > -1) {
							this.deletePhotos.push(filePath);
						}
						break;
					}
				}
			},
			isSendBack: function() {
				if (this.checkQualityProblem.sentBackDate != null && this.checkQualityProblem.sentBackDate > 0) {
					return true;
				} else {
					return false;
				}
			},
			isRepairUser: function() {
				var currentUserId = getUser().userId;
				var user = this.checkQualityProblem.repair;
				if (user == currentUserId) {
					return true;
				}
				return false;
			},
			isRegistUser: function() {
				var currentUserId = getUser().userId;
				var user = this.checkQualityProblem.registBy;
				if (user == currentUserId) {
					return true;
				}
				return false;
			},
			openHousePoint: function(house) {
				var self = this;
				var houseType = this.$store.state.global.houseTypeMap[house.house_type_id];
				var router = self.$f7router.navigate('/HousePoint', {
					props: {
						imageUrl: houseType.url,
						pointCount: 20,
						initialPoints: self.checkQualityProblem.problemValues,
						editable: false
					}
				});
			},
			formateDate: function(problem) {
				var date = '';
				if (problem != null) {
					date += DateUtil.dateToStr('yyyy-MM-dd HH:mm', problem) + ' ';
				}
				return date;
			},
			ensureAbnormalCloseSubmit: function() {
				var self = this;
				this.$f7.dialog.confirm("您确定提交？", "", function() {
					self.abnormalColseSubmit();
				});
			},
			abnormalColseSubmit: function() {
				let self = this;
				if(self.closeReason != "") {
					let closeRemark = "";
					if(self.closeReason == "其它") {
						closeRemark = self.closeRemark ==''? "其它": self.closeRemark;
					}else{
						closeRemark = self.closeReason;
					}
					let data = {
						checkQualityProblemId: self.checkQualityProblem.id,
						closeRemark: closeRemark,
					}
					var promise = request({
							url: '/api/checkQualityProblem/problemClose',
							method: 'POST',
							timeout: 60000 * 5,
							data: data,
							headers: {
								'Content-Type': 'application/x-www-form-urlencoded'
							}	 
						}).then(result => {
							if (result.success) {
								self.$f7.popup.close('#abnormalClosePopup', true);
								self.$f7.dialog.alert(result.msg, '问题关闭成功！');
								self.$f7router.back();
								self.$f7router.emit('problemStautsChange', result.element);
								if (self.form.tid != null) {
									self.$f7router.emit('deleteProblemRepair', self.form.tid);
								}
							} else {
								self.$f7.dialog.alert(result.msg, '问题关闭失败！');
							}
							self.$f7.preloader.hide();
						})
						.catch(error => {
							console.error(error);
							return Promise.resolve();
						});
				} else {
					this.$f7.dialog.alert('请选择问题关闭原因', '错误提示');
				}
			},
			saveTemporary: function() {
				var self = this;
				self.$f7.preloader.show();
				let promises = [];
				self.deletePhotos.forEach(photo => {
					let promise = FileUtil.remove(photo).then(() => {
						return Promise.resolve();
					}).catch((error) => {
						console.error(error);
						return Promise.resolve();
					});
					promises.push(promise);
				});
				Promise.all(promises).then(() => {
					let promises = [];
					self.form.photos.forEach(photo => {
						let promise = null;
						if (photo.indexOf(Common.directory().localeCheck) < 0) {
							let splits = photo.split('/');
							let filename = splits[splits.length - 1];
							let to = Common.directory().base + Common.directory().localeCheck + filename;
							promise = FileUtil.copy(photo, to);
						} else {
							promise = new Promise((resolve, reject) => {
								resolve(photo);
							});
						}
						promises.push(promise);
					});
					return Promise.all(promises);
				}).then((paths) => {
					let photos = [];
					paths.forEach(path => {
						photos.push(path);
					});
					self.form.photos = photos;
					self.form.checkQualityProblemId = self.checkQualityProblem.id;
					let sql = '';
					if (self.form.tid == null) {
						sql =
							"\
								insert into offline_local_check_repair( \
								checkquality_problem_id, offline_repair_image_file, \
								offline_repair_remark) \
								values (?, ?, ?) \
							";
					} else {
						sql =
							"\
							update offline_local_check_repair \
							set checkquality_problem_id = ?, offline_repair_image_file = ?, \
							offline_repair_remark = ? \
							where tid = '" +
							self.form.tid + "'";
					}
					var values = [
						self.form.checkQualityProblemId,
						JSON.stringify(self.form.photos),
						self.form.remark
					];
					return Common.executeSql(sql, values);
				}).then((result) => {
				
					self.$f7.dialog.alert('', '暂存问题成功');
					let rs = result.rs;
					self.$f7router.emit('saveTemporary', self.form.tid || rs.insertId);
					self.$f7.preloader.hide();
					self.$f7router.back();
				}).catch(error => {
					console.error(error);
					self.$f7.dialog.alert('', '暂存问题失败');
        			self.$f7.preloader.hide();
				});

			}
		},
		computed: {
			timeout: function() {
				try {
					var currentDate = new Date();
					var repairDeadline = this.checkQualityProblem.repairDeadline;
					if (currentDate > repairDeadline) {
						return true;
					}
				} catch (e) {}
				return false;
			}
		},
		watch: {
			'form.repair.userId': function(newVal, oldVal) {
				if (newVal != '' && oldVal != '') {
					var self = this;
					var param = {};
					param.checkQualityProblemId = self.checkQualityProblem.id;
					param.newRepairId = newVal;
					var promise = request({
						url: '/api/checkQualityRepair/changeRepair',
						method: 'get',
						timeout: 60000 * 5,
						params: param
					}).then(result => {
						if (result.success) {
							self.$f7.dialog.alert('修改整改人成功', '修改整改人成功');
							self.$f7router.back();
							self.$f7router.emit('problemChangeRepair', result.element);
							if (self.form.tid != null) {
								self.$f7router.emit('deleteProblemRepair', self.form.tid);
							}
						} else {
							self.checkQualityProblem.id = oldVal;
							self.$f7.smartSelect.get('#repairUserSmartSelect .smart-select').setValue(
								self.$store.state.global.userMap[oldVal].realname
							);
							self.$f7.dialog.alert('该问题已经由该人提交过来', '修改整改人失败');
						}
					}).catch(error => {
						console.error(error);
						return Promise.resolve();
					});

				}
			}
		},
		created: function() {

		},
		mounted: function() {
			var self = this;
			
			self.form.repair.userId = self.checkQualityProblem.repair;
			var currentUserId = getUser().userId;
			var repairUser = self.checkQualityProblem.repair;
			if (currentUserId == repairUser) {
				if (self.isRepairUser) {
					this.$nextTick(function() {
						if (self.$f7.smartSelect.get('#repairUserSmartSelect .smart-select') == undefined) {
							self.$nextTick(function() {
								self.$f7.smartSelect.get('#repairUserSmartSelect .smart-select').setValue(
									self.$store.state.global.userMap[self.form.repair.userId].realname
								);
							});
						} else {
							self.$f7.smartSelect.get('#repairUserSmartSelect .smart-select').setValue(
								self.$store.state.global.userMap[self.form.repair.userId].realname
							);
						}
					});
				}
				window.parent.db.transaction(function(tx) {
					var sql =
						"\
        	        select * from offline_local_check_repair \
        	        where checkquality_problem_id = '" +
						self.checkQualityProblem.id + "' \
        	    ";
					tx.executeSql(sql, [], function(tx, rs) {
						if (rs.rows.length != 0) {
							var row = rs.rows.item(0);
							self.form.photos = Common.strToJson(row.offline_repair_image_file);
							self.$refs.refTakePhoto.addPhotos(self.form.photos);
							self.form.remark = row.offline_repair_remark;
							self.form.tid = row.tid;
						}
					});
				}, function(error) {
					console.error(error);
				});
			}
			var projectId = self.$store.state.global.bidSectionMap[self.checkQualityProblem.bidSectionId].project_id;
			window.parent.db.transaction(function(tx) {
				var sql =
					"select id, app_permission " +
					"from tb_user " +
					"where id in ( " +
					"    select user_id from tb_user_project where project_id = '" + projectId + "' " +
					") " +
					"order by username ";
				tx.executeSql(sql, [], function(tx, rs) {
					for (var i = 0; i < rs.rows.length; i++) {
						var row = rs.rows.item(i);
						if (row.app_permission == '施工单位') {
							self.contractors.push(row.id);
						} else if (row.app_permission == '监理单位') {
							self.supervisors.push(row.id);
						} else if (row.app_permission == '建设单位') {
							self.constructors.push(row.id);
						}
					}
				});
			}, function(error) {
				console.error(error);
			});
		}
	}
</script>

<style scoped>

</style>
